package oylj.recycle.all_in_one.print;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Base64;
import android.util.Log;
import android.webkit.JavascriptInterface;

import com.csnprintersdk.csnio.CSNPOS;
import com.csnprintersdk.csnio.CSNUSBPrinting;

import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ImgPrintLib {
    private static final String TAG = "ImgPrintLib";

    private static final ExecutorService es = Executors.newScheduledThreadPool(30);
    private static final CSNPOS mPos = new CSNPOS();
    private boolean isInitialized;

    public ImgPrintLib(Context context){

        CSNUSBPrinting mUsb = new CSNUSBPrinting();
        mPos.Set(mUsb);
//        mUsb.SetCallBack(this);
        final UsbManager mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        if (deviceList.size() > 0) {
            while (deviceIterator.hasNext()) {
                final UsbDevice device = deviceIterator.next();
                if(device.getVendorId() == 4070){
                    es.submit(new TaskOpen(mUsb,mUsbManager,device,context));
                    isInitialized = true;
                    break;
                }
            }
        }
    }

    public boolean isInitialized() {
        return isInitialized;
    }
    public class TaskOpen implements Runnable
    {
        CSNUSBPrinting usb = null;
        UsbManager usbManager = null;
        UsbDevice usbDevice = null;
        Context context = null;

        public TaskOpen(CSNUSBPrinting usb, UsbManager usbManager, UsbDevice usbDevice, Context context)
        {
            this.usb = usb;
            this.usbManager = usbManager;
            this.usbDevice = usbDevice;
            this.context = context;
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            boolean isSuccess = usb.Open(usbManager,usbDevice,context);
            Log.d(TAG, "PrintLib: isSuccess "+isSuccess);
        }
    }

    @JavascriptInterface
    public void imgPrint(String base64String) {
        // 解码 Base64 字符串为字节数组
        byte[] decodedBytes = Base64.decode(base64String, Base64.DEFAULT);

        // 使用字节数组创建 Bitmap 对象
        Bitmap bitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
        printTicket(bitmap);
    }

    public int printTicket(Bitmap bitmap) {
        int bPrintResult = 0;

        byte[] status = new byte[1];
        if (mPos.POS_RTQueryStatus(status, 3, 1000, 2)) {

            if ((status[0] & 0x08) == 0x08)   //判断切刀是否异常
                return bPrintResult = -2;

            if ((status[0] & 0x40) == 0x40)   //判断打印头是否在正常值范围内
                return bPrintResult = -3;

            if (mPos.POS_RTQueryStatus(status, 2, 1000, 2)) {

                if ((status[0] & 0x04) == 0x04)    //判断合盖是否正常
                    return bPrintResult = -6;
                if ((status[0] & 0x20) == 0x20)    //判断是否缺纸
                    return bPrintResult = -5;
                else {

                    mPos.POS_Reset();
                    mPos.POS_PrintPicture(bitmap, 576, 1, 0);
                    mPos.POS_FeedLine();
                    mPos.POS_FeedLine();
                    mPos.POS_FeedLine();
                    mPos.POS_FeedLine();


                    try {
                        Thread.currentThread();
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                mPos.POS_Beep(1, 5);
                mPos.POS_FullCutPaper();
            }

        } else {
            return bPrintResult = -8;           //查询失败
        }

        return bPrintResult = 0;
    }

    public String resultCodeToString(int code) {
        switch (code) {
            case 3:
                return "出纸口有未取小票，请注意及时取走小票";
            case 2:
                return "紙将尽 且 出纸口有未取小票，请注意更换纸卷 和 及时取走小票";
            case 1:
                return "紙将尽，请注意更换纸卷";
            case 0:
                return " ";
            case -1:
                return "未打印小票，请检查是否卡纸";
            case -2:
                return "切刀异常，请手动排除";
            case -3:
                return "打印头过热，请等待打印机冷却";
            case -4:
                return "打印机脱机";
            case -5:
                return "打印机缺纸";
            case -6:
                return "上盖打开";
            case -7:
                return "实时状态查询失败";
            case -8:
                return "查询状态失败，请检查通讯端口是否连接正常";
            case -9:
                return "打印过程中缺纸，请检查单据完整性";
            case -10:
                return "打印过程中上盖开启，请重新打印";
            case -11:
                return "连接中断，请确认打印机是否连线";
            case -12:
                return  "请取走打印完的票据后，再进行打印！";
            case -13:
            default:
                return "未知错误";
        }
    }
}
